package com.yunhe.option.service.base.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.option.domain.base.AcceptanceSituation;
import com.yunhe.option.repository.base.AcceptanceSituationRepository;
import com.yunhe.option.service.base.AcceptanceSituationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

/**
 * 验收情况类型Service
 * @desc 验收情况类型服务类实现
 * @author anmeiyi
 */
@Service
public class AcceptanceSituationServiceImpl implements AcceptanceSituationService {
    @Autowired
    private AcceptanceSituationRepository acceptanceSituationRepository;

    private void processBeforeSave(AcceptanceSituation acceptanceSituation)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断验收情况类型代码、编号、标题是否为空
        if(acceptanceSituation.getCode() == null
                || StringUtil.isEmpty(acceptanceSituation.getName())
                || StringUtil.isEmpty(acceptanceSituation.getTitle())) {
            throw new ArgumentErrorException("验收情况类型代码、编号、标题不能为空");
        }
        //判断代码是否已存在
        AcceptanceSituation categoryByCode = this.findByCode(acceptanceSituation.getCode());
        if(categoryByCode != null) {
            if(acceptanceSituation.getId() == null || categoryByCode.getId().longValue() != acceptanceSituation.getId().longValue()) {
                throw new UniqueConstraintsException("该验收情况类型代码已存在");
            }
        }
        //判断编号是否已存在
        AcceptanceSituation categoryByName = this.findByName(acceptanceSituation.getName());
        if(categoryByName != null) {
            if(acceptanceSituation.getId() == null || categoryByName.getId().longValue() != acceptanceSituation.getId().longValue()) {
                throw new UniqueConstraintsException("该验收情况类型编号已存在");
            }
        }
        //如果序号为空，则默认等于代码
        if(acceptanceSituation.getSn() == null && acceptanceSituation.getCode() != null) {
            acceptanceSituation.setSn(acceptanceSituation.getCode());
        }
    }

    /**
     * 新增验收情况类型
     * @param acceptanceSituation 验收情况类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public AcceptanceSituation createAcceptanceSituation(AcceptanceSituation acceptanceSituation)
            throws ArgumentErrorException, UniqueConstraintsException {
        acceptanceSituation.setId(null);
        processBeforeSave(acceptanceSituation);
        return acceptanceSituationRepository.save(acceptanceSituation);
    }

    /**
     * 删除验收情况类型
     * @param acceptanceSituationId 验收情况类型Id
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteAcceptanceSituation(Long acceptanceSituationId) {
        acceptanceSituationRepository.deleteById(acceptanceSituationId);
    }

    /**
     * 更新验收情况类型(全部字段）
     * @param acceptanceSituation 验收情况类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public AcceptanceSituation updateAcceptanceSituation(AcceptanceSituation acceptanceSituation)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = acceptanceSituation.getId() != null && acceptanceSituationRepository.existsById(acceptanceSituation.getId());
        if(!exists) {
            throw new ObjectNotFoundException("找不到ID为" + acceptanceSituation.getId() + "的验收情况类型");
        }
        processBeforeSave(acceptanceSituation);
        return acceptanceSituationRepository.save(acceptanceSituation);
    }

    /**
     * 更新验收情况类型（部分字段）
     * @param acceptanceSituationId
     * @param code
     * @param name
     * @param title
     * @param sn
     * @param activity
     * @param acceptanceTime
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public AcceptanceSituation updateAcceptanceSituation(Long acceptanceSituationId, Long code, String name, String title, Long sn, Boolean activity, Date acceptanceTime)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        AcceptanceSituation acceptanceSituation = this.findByAcceptanceSituationId(acceptanceSituationId);
        if(acceptanceSituation == null) {
            throw new ObjectNotFoundException("找不到ID为" + acceptanceSituationId + "的验收情况类型");
        }
        Optional.ofNullable(code).ifPresent(acceptanceSituation::setCode);
        Optional.ofNullable(name).ifPresent(acceptanceSituation::setName);
        Optional.ofNullable(title).ifPresent(acceptanceSituation::setTitle);
        Optional.ofNullable(sn).ifPresent(acceptanceSituation::setSn);
        Optional.ofNullable(activity).ifPresent(acceptanceSituation::setActivity);
        Optional.ofNullable(acceptanceTime).ifPresent(acceptanceSituation::setAcceptanceTime);
        processBeforeSave(acceptanceSituation);
        return acceptanceSituationRepository.save(acceptanceSituation);
    }

    /**
     * 获得全部验收情况类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Iterable<AcceptanceSituation> findIndustryCategories() {
        return acceptanceSituationRepository.findAll(QueryUtil.defaultSort());
    }

    /**
     * 根据编号获得验收情况类型对象
     * @param name
     */
    private AcceptanceSituation findByName(String name) {
        return acceptanceSituationRepository.findByName(name);
    }

    /**
     * 根据代码获得验收情况类型对象
     * @param code
     */
    private AcceptanceSituation findByCode(Long code) {
        return acceptanceSituationRepository.findByCode(code);
    }

    /**
     * 根据ID获得验收情况类型对象
     * @param acceptanceSituationId
     * @return
     */
    private AcceptanceSituation findByAcceptanceSituationId(Long acceptanceSituationId) {
        return acceptanceSituationRepository.findById(acceptanceSituationId).orElse(null);
    }
}
